import { ethers } from "ethers";
import { createContext, useContext, useState, useEffect, useCallback, useRef } from "react";
import type { ReactNode } from "react";
import { disconnectWallet, setAddress, setApproveAddress, setChainId, setNativeSymbol, updateBalance } from "@/store/slices/walletSlice";
import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { chainIdToNativeSymbol } from "./wallet-util";

// 定义Provider上下文接口
interface ProviderContextType {
  provider: ethers.providers.Web3Provider | null;
  setProvider: (provider: ethers.providers.Web3Provider | null) => void;
}

// 创建Provider上下文，使用null作为默认值
const ProviderContext = createContext<ProviderContextType | null>(null);

// Provider包装组件
export const ProviderContextProvider = ({ children }: { children: ReactNode }) => {
  const [provider, setProvider] = useState<ethers.providers.Web3Provider | null>(null);
  
  useEffect(() => {
    console.log('===provider in context===', provider);
  }, [provider]);
  
  return (
    <ProviderContext.Provider value={{ provider, setProvider }}>
      {children}
    </ProviderContext.Provider>
  );
};

// 自定义hook，用于访问Provider上下文
export const useProviderHook = () => {
  const context = useContext(ProviderContext);
  
  if (!context) {
    throw new Error('useProviderHook must be used within a ProviderContextProvider');
  }
  
  return context;
};
// 断开连接 hook
export const useDisConnect = () => {
  const { setProvider } = useProviderHook();
  const dispatch = useAppDispatch();
  const disConnect = async () => {
    setProvider(null);
    const originalChainId = await window.ethereum.request({ method: "eth_chainId" }); 
    let tId = '';
    Object.keys(chainIdToNativeSymbol).some((chainId) => {
      if (chainId === originalChainId) {
        tId = chainId;
        return true;
      } else {
        return false
      }
    });
    await window.ethereum.request({
      method: "wallet_switchEthereumChain",
      params: [{ chainId: tId }],
    });
    await window.ethereum.request({
      method: "wallet_switchEthereumChain",
      params: [{ chainId: originalChainId }],
    });
    dispatch(disconnectWallet());
  }
  return disConnect;
}
export const useUpdateBalance = () => {
  const { provider } = useProviderHook();
  const dispatch = useAppDispatch();
  const providerRef = useRef<ethers.providers.Web3Provider | null>(null);
  useEffect(() => {
    providerRef.current = provider;
  }, [provider])
  const updateBalanceHook = async () => {
    if (providerRef.current) {
      const signer = providerRef.current.getSigner();
      const address = await signer.getAddress();
      const balance = await providerRef.current.getBalance(address);
      dispatch(updateBalance(ethers.utils.formatEther(balance)));
    }
  }
  return updateBalanceHook;
}

export const useUpdateAddress = () => {
  const updateBalanceHook = useUpdateBalance()
  const { provider } = useProviderHook();
  const dispatch = useAppDispatch();
  const providerRef = useRef<ethers.providers.Web3Provider | null>(null);
  
  useEffect(() => {
    providerRef.current = provider;
  }, [provider])
  const updateAddressHook = async (addressList: string[]) => {
    console.log('lc----', providerRef.current)
    if (providerRef.current) {
      const signer = providerRef.current.getSigner();
      const address = await signer.getAddress();
      dispatch(setApproveAddress(addressList));
      dispatch(setAddress(address))
      updateBalanceHook()
    }
  }
  return updateAddressHook;
}

